package struts.action;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.EventDispatchAction;
import org.springframework.beans.factory.annotation.Autowired;

import struts.form.LoginForm;
import util.CookieUtil;
import bean.UserObject;
import biz.LoginBiz;

public class LoginAction extends EventDispatchAction {
	@Autowired
	LoginBiz loginBiz;

	@Autowired
	UserObject userObject;

	/**
	 * 初期处理
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		saveToken(request);
		form.reset(mapping, request);
		return mapping.findForward("self");
	}

	/**
	 * 登录处理
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

		LoginForm loginForm = (LoginForm) form;

		String userId = loginForm.getUserId();
		String password = loginForm.getPassword();

		UserObject uo = loginBiz.selectUserObject(userId, password);

		if (uo == null) {
			ActionMessages errors = new ActionMessages();
			errors.add("userId", new ActionMessage("Z0000X0001"));
			saveErrors(request, errors);
			return mapping.getInputForward();
		}

		// Save uo Object into session
		request.getSession().setAttribute(UserObject.USER_OBJECT_KEY, uo);

		// Copy the uo Object into userObject in order to
		// we can use the useObject anywhere through Spring. 
		try {
			PropertyUtils.copyProperties(userObject, uo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// set default value as -1,
		// means when close browser lost the cookie.
		int expiry = -1;
		Cookie ticket = null;
		if(StringUtils.isEmpty(loginForm.getCookieTime())) {
			// Generate a cookie with the useId and password
			ticket = CookieUtil.GenerateCookie(userId, password, expiry);
			response.addCookie(ticket);
		} else {
			expiry = Integer.parseInt(loginForm.getCookieTime());
			// Generate a cookie with the useId and password
			ticket = CookieUtil.GenerateCookie(userId, password, expiry);
			response.addCookie(ticket);
		}

		return mapping.findForward("sucess");
	}
}
